<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const username = ref('')
const password = ref('')
const errorMessage = ref('')
const isLoading = ref(false)

interface LoginResponse {
  code: number
  message: string
  data: {
    token: string
  } | null
}

const message = useMessage()
const userStore = useUserStore()

const goLogin = async () => {
  // 输入验证
  if (!username.value || !password.value) {
    errorMessage.value = '用户名和密码不能为空'
    return
  }

  isLoading.value = true
  errorMessage.value = ''

  try {
    console.log('开始登录请求，请求数据:', {
      username: username.value,
      password: '***'
    })

    const response = await fetch('http://localhost:8080/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username.value,
        password: password.value
      })
    })

    // 获取响应内容
    const responseText = await response.text()
    console.log('登录响应:', responseText)

    if (!responseText) {
      throw new Error('服务器返回空响应')
    }

    // 解析响应
    const result = JSON.parse(responseText) as LoginResponse
    console.log('解析后的响应:', result)

    if (result.code === 200 && result.data?.token) {
      // 使用 store 的方法来设置登录状态
      userStore.setLoginState(result.data.token)
      
      // 跳转到首页或重定向页面
      const redirect = router.currentRoute.value.query.redirect as string
      await router.push(redirect || '/')
      
      message.success('登录成功')
    } else {
      throw new Error(result.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    errorMessage.value = error.message || '网络错误，请检查网络连接'
    // 使用 store 的方法来清除登录状态
    userStore.clearLoginState()
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="login-body">
    <div class="login-center">
      <div class="login-title wow fadeInDown">
        <p>智慧农场数据大屏登录</p>
      </div>
      <div class="login-form">
        <div class="form-title wow fadeInDown">用户登录</div>
        <div class="login-input wow fadeInLeft">
          <input v-model="username" type="text" placeholder="用户名">
        </div>
        <div class="login-input wow fadeInRight">
          <input v-model="password" type="password" placeholder="密码">
        </div>
        <div class="info">
          <div class="remember wow fadeInLeft">
            <input type="checkbox">
            <span>记住密码</span>
          </div>
          <div class="forget wow fadeInRight">
            <span class="forget-password">忘记密码？</span>
            <span class="divider">|</span>
            <router-link to="/register" class="register-link">立即注册</router-link>
          </div>
        </div>
        <div v-if="errorMessage" class="error-message wow fadeInUp">
          {{ errorMessage }}
        </div>
        <div class="login-button wow fadeInUp" @click="goLogin" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-body {
  width: 100vw;
  height: 100vh;
  background-image: url('@/assets/background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-body::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 21, 41, 0.7);
  z-index: 1;
}

.login-center {
  width: 500px;
  padding: 40px;
  position: relative;
  z-index: 2;
}

.login-title {
  text-align: center;
  margin-bottom: 40px;
}

.login-title p {
  color: #00e4ff;
  font-size: 36px;
  font-weight: bold;
  text-shadow: 0 0 15px rgba(0,228,255,0.8);
}

.login-form {
  background: rgba(0, 24, 48, 0.8);
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 0 25px rgba(0,228,255,0.2);
  font-size: 16px;
}

.form-title {
  color: #00e4ff;
  font-size: 24px;
  text-align: center;
  margin-bottom: 30px;
}

.login-input {
  position: relative;
  margin-bottom: 20px;
}

.login-input input {
  width: 100%;
  height: 45px;
  background: rgba(0,228,255,0.1);
  border: 1px solid #00e4ff;
  border-radius: 5px;
  padding: 0 15px;
  color: #fff;
  font-size: 16px;
}

.login-input input::placeholder {
  color: rgba(0,228,255,0.6);
}

.info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  color: #00e4ff;
}

.remember {
  display: flex;
  align-items: center;
  gap: 5px;
}

.remember input[type="checkbox"] {
  width: 16px;
  height: 16px;
  background: transparent;
  border: 1px solid #00e4ff;
}

.forget {
  cursor: pointer;
  display: flex;
  gap: 10px;
  align-items: center;
}

.forget-password:hover,
.register-link:hover {
  text-decoration: underline;
}

.divider {
  color: rgba(0,228,255,0.6);
}

.register-link {
  color: #00e4ff;
  text-decoration: none;
}

.login-button {
  width: 100%;
  height: 45px;
  background: #00e4ff;
  border: none;
  border-radius: 5px;
  color: #001529;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.login-button:hover {
  background: #00b4cc;
}

.login-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 动画效果 */
.wow {
  animation-duration: 1s;
}

.fadeInDown {
  animation-name: fadeInDown;
}

.fadeInLeft {
  animation-name: fadeInLeft;
}

.fadeInRight {
  animation-name: fadeInRight;
}

.fadeInUp {
  animation-name: fadeInUp;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translate3d(0, -100%, 0);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translate3d(100%, 0, 0);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translate3d(0, 100%, 0);
  }
  to {
    opacity: 1;
    transform: none;
  }
}

.error-message {
  color: #ff4d4f;
  text-align: center;
  margin-bottom: 20px;
  font-size: 14px;
}
</style>
